<?php
// +----------------------------------------------------------------------
// | 海豚PHP框架 [ DolphinPHP ]
// +----------------------------------------------------------------------
// | 版权所有 2016~2019 广东卓锐软件有限公司 [ http://www.zrthink.com ]
// +----------------------------------------------------------------------
// | 官方网站: http://dolphinphp.com
// +----------------------------------------------------------------------

namespace app\wh\api;

use app\admin\controller\Config;
use app\common\controller\ApiController;
use app\wh\admin\Stock;
use think\App;
use app\wh\model\Material as MaterialModel;
use app\wh\model\App as AppModel;
use app\wh\model\Stock as StockModel;
use app\wh\model\StockType as StockTypeModel;
use app\wh\model\Color as ColorModel;
use app\admin\model\Config as ConfigModel;
use think\Db;

/**
 * 仓库公开控制器
 * @package app\user\admin
 */
class Index extends ApiController
{
    public function __construct(App $app = null)
    {
        parent::__construct($app);

        $this->is_member();
    }

    /**
     * 监听
     */
    public function timer(){
        success('');
    }
    /**
     * 过滤数字
     */
    public function filterNumber($number = 0){
        $number = floatval($number);
        if(empty($number) || $number < 0)errors('请输入正常的数量');
        return $number;
    }
    /**
     * 菜单配置
     */
    public function getMenu(){

        $menu = AppModel::getMenu(0,$this->member);

        success('', array('list' => $menu));
    }
    /**
     * 产品详情
     */
    public function detail(){
        // 获取参数
        $data = input('');

        if(!empty($data['search'])){
            $search_where = "model like '%{$data['search']}%'";
            $data['stock_sn'] = Db::name('wh_stock')->where(['type_pid'=>$data['type_pid']])->where($search_where)->value('stock_sn');
        }
        $where[] = ['s.stock_sn','=',$data['stock_sn']];

        $info = $this->stockInfo($data['stock_sn']);

        if(empty($info))errors('该产品不存在');

        $info['same_stock'] = '';
        $same_stock_sn = StockModel::addSameStock($info['stock_sn']);
        if(!empty($same_stock_sn))$info['same_stock'] = $this->stockInfo($same_stock_sn);

        //档案信息
        $info['order_list'] = [];
        if(!empty($data['archives_sn'])){
            //主物料的颜色自编码
            $color_sn_main = $info['color_sn'];
            if(!empty($info['main_id'])){
                $stock_sn_main = StockModel::addSameStock($info['stock_sn']);
                $color_sn_main = Db::name('wh_stock')->where(['stock_sn'=>$stock_sn_main])->value('color_sn');
            }

            $archives_sns = "{$data['archives_sn']},";
            $where = [];
            $where[] = ['c.archives_sn','in',$data['archives_sn']];
            $where[] = ['c.color_sn','=',$color_sn_main];
            $info['order_list'] = Db::name('wh_order_color')
                ->alias('c')
                ->leftJoin('mill_order o','c.order_id=o.id')
                ->field('o.archives_sn,o.engineering,c.row_area')
                ->where($where)
                ->select();
            if(empty($info['order_list']))errors("档案号[{$data['archives_sn']}]，定色不匹配");
            else{
                foreach ($info['order_list'] as $v){
                    $archives_sns = str_replace("{$v['archives_sn']},","",$archives_sns);
                }
            }
            if(!empty($archives_sns))errors("档案号[{$archives_sns}]，定色不匹配");
        }

        success('',$info);
    }
    /**
     * 产品信息
     */
    public function stockInfo($stock_sn = ''){

        $where[] = ['s.stock_sn','=',$stock_sn];

        $info = Db::name('wh_stock')
            ->alias('s')
            ->field('s.*,t.main_id,t.title as type_pname,tt.title as type_name,tt2.title as type_name2,tt3.title as type_name3,ss.title_abb as supplier_name,q.title as quality')
            ->leftJoin('wh_stock_type t','t.id=s.type_pid')
            ->leftJoin('wh_stock_type tt','tt.id=s.type_id')
            ->leftJoin('wh_stock_type tt2','tt2.id=s.type_id2')
            ->leftJoin('wh_stock_type tt3','tt3.id=s.type_id3')
            ->leftJoin('wh_supplier ss','ss.id=s.supplier_id')
            ->leftJoin('wh_supplier_quality q','q.id=s.quality')
            ->where($where)
            ->find();

        if(empty($info))return '';

        if(!empty($info['type_name2']))$info['type_name'] = "{$info['type_name2']}";
        if(!empty($info['type_name3']))$info['type_name'] .= ">{$info['type_name3']}";

        $info['type_name'] = "{$info['type_pname']}>{$info['type_name']}";
        $info['material_name'] = $info['title'];
        $info['sum_number'] = StockModel::getSumNumber($info);
        $info['join_time'] = date('Y-m-d H:i');

        $info['type_name_str'] = "类别：{$info['type_name']}";
        $info['supplier_name_str'] = "供应商：{$info['supplier_name']}";
        $info['material_name_str'] = "名称：{$info['material_name']}";
        $info['model_str'] = "规格型号：{$info['model']}";
        if(in_array($info['type_pid'],ColorModel::$type_pid_arr))$info['model_str'] = "厂家色号：{$info['model']}";
        $info['lot_sn_str'] = (!empty($info['lot_sn']))?"批号：{$info['lot_sn']}":'';
        $info['sum_number_str'] = "库存：{$info['sum_number']} kg";
        $info['sum_num_str'] = "数量：{$info['num']}";

        return $info;
    }
    /**
     * 搜索的产品列表
     */
    public function searchLists(){
        // 获取参数
        $data = input('');
        $pindex = max(1, intval(input('page',1)));
        $psize = 1;

        $list = [];
        if(!empty($data['search'])){
            $search_where = "s.model like '%{$data['search']}%'";

            $where[] = ['s.type_pid','=',$data['type_pid']];

            $list = Db::name('wh_stock')
                ->alias('s')
                ->field("s.stock_sn,s.title,s.model,ss.title_abb as supplier_title,CONCAT(s.title,'(',s.model,')','：',ss.title_abb) as title_str")
                ->leftJoin('wh_supplier ss','ss.id=s.supplier_id')
                ->where($where)
                ->where($search_where)
                ->select();
        }

        $total = 9999;
        success('', array('list' => $list, 'pagesize' => $psize, 'total' => $total, 'pindex' => $pindex, 'total_pages' => 1));
    }
    /**
     * 入库
     * @return mixed
     */
    public function joinGoods()
    {
        $user = $this->member;

        if ($this->request->isPost()) {
            // 获取post数据
            $data = $this->request->post();

            $type_pid = input('type_pid');
            if (empty($data['stock_sn']))errors('请扫码');
            //if (empty($data['material_sn']))errors('请选择采购单');
            if (empty($data['number']))errors('请输入入库数量');
            $data['number'] = $this->filterNumber($data['number']);

            $where = ['stock_sn'=>$data['stock_sn']];
            $info = Db::name('wh_stock')->where($where)->find();
            $info['material_sn'] = input('material_sn');
            $info['note'] = input('note');
            if(!empty($info['note']))$info['cate'] = 1;//1采购单入库，2领用，3退还

            if(empty($info))errors('该产品不存在');
            if(!empty($type_pid) && $info['type_pid'] != $type_pid)errors('入库分类错误，无法入库');
            //记录
            $re = StockModel::log(0,$info,$data['number'],$user['uid']);
            if(!empty($re['msg']))errors($re['msg']);

            success('操作成功',[]);
        }

        errors('操作异常');
    }
    /**
     * 出库
     * @return mixed
     */
    public function outGoods()
    {
        $user = $this->member;

        if ($this->request->isPost()) {
            // 获取post数据
            $data = $this->request->post();

            $type_pid = input('type_pid');
            if (empty($data['stock_sn']))errors('请扫码');
            if (empty($data['number']))errors('请输入出库数量');
            $data['number'] = $this->filterNumber($data['number']);

            $where = ['stock_sn'=>$data['stock_sn']];
            $info = Db::name('wh_stock')->where($where)->find();
            $info['note'] = input('note');

            if(empty($info))errors('该产品不存在');
            if(!empty($type_pid) && $info['type_pid'] != $type_pid)errors('出库分类错误，无法出库');
            //记录
            $re = StockModel::log(1,$info,$data['number'],$user['uid']);
            if(!empty($re['msg']))errors($re['msg']);

            success('操作成功',[]);
        }

        errors('操作异常');
    }
    /**
     * 盘存
     * @return mixed
     */
    public function takeInventory()
    {
        $user = $this->member;

        if ($this->request->isPost()) {
            // 获取post数据
            $data = $this->request->post();
            $data['number'] = trim($data['number']);

            $type_pid = input('type_pid');
            if (empty($data['stock_sn']))errors('请扫码');
            if (count($data['number']) == 0)errors('请输入盘存数量');
            $data['number'] = floatval($data['number']);

            $where = ['stock_sn'=>$data['stock_sn']];
            $info = Db::name('wh_stock')->where($where)->find();

            if(empty($info))errors('该产品不存在');
            if(!empty($type_pid) && $info['type_pid'] != $type_pid)errors('盘存分类错误，无法盘存');

            //库存数量
            if(is_numeric($data['num']))$data['num'] = intval($data['num']);

            //记录
            $re = StockModel::takeLog(2,$info,$data['number'],$user['uid']);
            if(!empty($re['msg']))errors($re['msg']);

            success('操作成功',[]);
        }

        errors('操作异常');
    }
    /**
     * 直接入库
     * @return mixed
     */
    public function directJoinGoods_old()
    {
        $user = $this->member;

        if ($this->request->isPost()) {
            // 获取post数据
            $data = $this->request->post();

            $type_pid = input('type_pid');
            if (empty($data['stock_sn']))errors('请扫码');
            if (empty($data['number']))errors('请输入入库数量');
            $data['number'] = $this->filterNumber($data['number']);

            $where = ['stock_sn'=>$data['stock_sn']];
            $info = Db::name('wh_stock')->where($where)->find();
            $info['note'] = input('note');

            if(empty($info))errors('该产品不存在');
            if(!empty($type_pid) && $info['type_pid'] != $type_pid)errors('入库分类错误，无法入库');
            //记录
            $re = StockModel::log(0,$info,$data['number'],$user['uid']);
            if(!empty($re['msg']))errors($re['msg']);

            success('操作成功',[]);
        }

        errors('操作异常');
    }
    /**
     * 稀油入库
     * @return mixed
     */
    public function addJoinGoods()
    {
        $user = $this->member;

        if ($this->request->isPost()) {

            $type_pid = input('type_pid');
            $stock_sn = input('stock_sn');
            $number = input('number');
            if (empty($stock_sn))errors('请扫码');
            if (empty($number))errors('请输入入库数量');
            $number = $this->filterNumber($number);

            //油漆类的库存信息
            $stock = $info = Db::name('wh_stock')->where(['stock_sn'=>$stock_sn])->find();
            if(empty($info))errors('该产品不存在');
            //判断油漆库类型是否关联稀油库
            $link_type_ids = StockTypeModel::getLinkTypeIds($info);

            if(empty($link_type_ids['level1']))errors('该库存未做关联');
            if($link_type_ids['level1'] != $type_pid)errors('入库分类错误，无法入库');

            $order = 'u.create_time desc';
            //根据扫码编号获取最近的《油漆库》领用记录
            $where = [['u.stock_sn','=',$stock_sn]];

            $use_log = Db::name('wh_stock_use_log')->alias('u')->where($where)->order($order)->find();
            if(empty($use_log))errors('没有领用记录');
            $use_sn = $use_log['use_sn'];

            //判断是不是稀油，不是则新增，并退还原油漆剩余

            //同步新增同规格不同物料类别的库存
            if($info['type_pid'] != $type_pid)$stock_sn = StockModel::addSameStock($stock_sn);

            //稀油的库存信息
            $where = ['stock_sn'=>$stock_sn];
            $info = Db::name('wh_stock')->where($where)->find();
            $type_title = Db::name('wh_stock_type')->where(['id'=>$info['type_id']])->value('title');
            if(empty($info))errors('该产品不存在');
            //分类信息
            $type_info = Db::name('wh_stock_type')->where(['id'=>$type_pid])->find();

            $info['post_number'] = $number;
            //稀油的入库记录
            StockModel::log(0,$info,$info['post_number'],$user['uid']);

            //退还记录，是退还至油漆类，而不是稀油类
            $info = $stock;//更换回油漆类的库存信息
            $info['cate'] = 3;//1采购单入库，2领用，3退还
            $info['use_number'] = Db::name('wh_stock_use_log')->where(['use_sn'=>$use_sn])->sum('number');
            $info['list'] = Db::name('wh_stock_use_log')->where(['use_sn'=>$use_sn])->select();
            $info['post_number'] = $number;
            $info['post_number2'] = $number2 = $number*$type_info['main_scale'];//稀油退还成油漆的折算比例：0.6

            $i = 1;
            $count = count($info['list']);
            foreach ($info['list'] as &$v){

                //分配到的数量
                $area__number = $number;//记录到退还记录，未折算的数量
                $area__number2 = $number2;//记录到覆盖率，稀油退还成油漆的折算比例：0.6
                //如果不是最后一个物料，则继续分配数量和比例
                if($i != $count){
                    //面积比例
                    $area_scale = round(($v['number']/$info['use_number']),4);
                    //分配到的数量
                    $area__number = round(($info['post_number']*$area_scale),2);
                    $area__number2 = round(($info['post_number2']*$area_scale),2);
                    //总数量-分配到的数量
                    $number -= $area__number;
                    $number2 -= $area__number2;
                }

                $info['order_id'] = $v['order_id'];
                $info['archives_sn'] = $v['archives_sn'];
                if(!empty($type_title))$info['note2'] = $type_title;
                //仅记录油漆类的退还记录
                $re = StockModel::log(0,$info,$area__number,$user['uid'],false);
                $log_id = '';
                if(!empty($re['log_id']))$log_id = $re['log_id'];

                $v['post_number'] = $area__number2;
                $v['log_id_back'] = $log_id;

                $i++;
            }

            StockModel::useLog(0,$info,$user['uid']);

            success('操作成功',[]);
        }

        errors('操作异常');
    }
    /**
     * 铝卷入库
     * @return mixed
     */
    public function lvJoinGoods()
    {
        $user = $this->member;

        if ($this->request->isPost()) {
            // 获取post数据
            $data = $this->request->post();

            $type_pid = input('type_pid');
            if (empty($data['stock_sn']))errors('请扫码');
            if (empty($data['material_sn']))errors('请选择采购单');
            if (empty($data['goods_id']))errors('请选择铝卷');
            if (empty($data['number']))errors('请输入入库数量');
            $data['number'] = $this->filterNumber($data['number']);

            $where = ['stock_sn'=>$data['stock_sn']];
            $info = Db::name('wh_stock')->where($where)->find();

            if(empty($info))errors('该产品不存在');
            if(!empty($type_pid) && $info['type_pid'] != $type_pid)errors('入库分类错误，无法入库');

            $goods = Db::name('wh_material_goods')->where(['id'=>$data['goods_id']])->find();
            if($info['supplier_id'] != $goods['supplier_id'] || $info['model'] != $goods['model'])errors('规格不匹配，不能入库');

            $msg = '操作成功';
            //如果库存 > 0，则生成新库存
            if($info['number'] > 0 && 1==2){
                //新增库存
                $info['uid'] = $user['uid'];
                $info['quality'] = $goods['quality'];
                $info['lot_sn'] = $goods['lot_sn'];
                $info['model2'] = $goods['lot_sn'];

                $stock_sn = StockModel::getStockSn($info);
                //更新采购单里的物料码
                Db::name('wh_material_goods')->where(['id'=>$goods['id']])->update(['stock_sn'=>$stock_sn]);

                $where = ['stock_sn'=>$stock_sn];

                $msg = '该铝卷入库成新的铝卷产品，请打印新的码';
            }
            //相反，则更新库存，材质及批号信息
            else{
                //更新
                $update = [
                    'quality'       =>  $goods['quality'],
                    'lot_sn'        =>  $goods['lot_sn'],
                ];
                Db::name('wh_stock')->where(['id'=>$info['id']])->update($update);
            }
            $info = Db::name('wh_stock')->where($where)->find();
            $info['material_sn'] = $goods['material_sn'];
            $info['goods_id'] = $goods['id'];

            //记录
            $re = StockModel::log(0,$info,$data['number'],$user['uid']);
            if(!empty($re['msg']))errors($re['msg']);

            success($msg,[]);
        }

        errors('操作异常');
    }
    /**
     * 铝卷出库
     * @return mixed
     */
    public function lvOutGoods()
    {
        $user = $this->member;

        if ($this->request->isPost()) {
            // 获取post数据
            $data = $this->request->post();

            $type_pid = input('type_pid');
            if (empty($data['stock_sn']))errors('请扫码');
            if (!is_numeric($data['number']))errors('请输入剩余量');
            if ($data['number']<0)errors('请输入正常的数量');
            $data['number'] = floatval($data['number']);

            $where = ['stock_sn'=>$data['stock_sn']];
            $info = Db::name('wh_stock')->where($where)->find();

            if(empty($info))errors('该产品不存在');
            if(!empty($type_pid) && $info['type_pid'] != $type_pid)errors('出库分类错误，无法出库');

            //实际出库量=库存-剩余量
            $data['number'] = $info['number']-$data['number'];

            //记录
            $re = StockModel::log(1,$info,$data['number'],$user['uid']);
            if(!empty($re['msg']))errors($re['msg']);

            success('操作成功',[]);
        }

        errors('操作异常');
    }
    /**
     * 铝板入库
     * @return mixed
     */
    public function lbJoinGoods()
    {
        $user = $this->member;

        if ($this->request->isPost()) {
            // 获取post数据
            $data = $this->request->post();

            $type_pid = input('type_pid');
            //if (empty($data['stock_sn']))errors('请扫码');
            //if (empty($data['material_sn']))errors('请选择采购单');
            if (empty($data['goods_id']))errors('请选择铝板');

            $goods = Db::name('wh_material_goods')->where(['id'=>$data['goods_id']])->find();
            if(empty($goods))errors('该铝板不存在');

            $data['stock_sn'] = $goods['stock_sn'];
            $where = ['stock_sn'=>$data['stock_sn']];
            $info = Db::name('wh_stock')->where($where)->find();

            if(empty($info))errors('该库存不存在');
            if(!empty($type_pid) && $info['type_pid'] != $type_pid)errors('入库分类错误，无法入库');
            if($info['supplier_id'] != $goods['supplier_id'] || $info['model'] != $goods['model'])errors('规格不匹配，不能入库');
            $data['number'] = $goods['number'];//重量
            $info['material_sn'] = $goods['material_sn'];
            $info['goods_id'] = $goods['id'];

            //总库存数量=库存数量+入库数量
            $data['num'] = $info['num'] + $goods['num'];

            $msg = '操作成功';

            //记录
            $re = StockModel::log(0,$info,$data['number'],$user['uid']);
            if(!empty($re['msg']))errors($re['msg']);

            success($msg,[]);
        }

        errors('操作异常');
    }
    /**
     * 铝板出库
     * @return mixed
     */
    public function lbOutGoods()
    {
        $user = $this->member;

        if ($this->request->isPost()) {
            // 获取post数据
            $data = $this->request->post();

            $type_pid = input('type_pid');
            if (empty($data['stock_sn']))errors('请扫码');
            if (!is_numeric($data['number']))errors('请输入剩余量');
            if ($data['number']<0)errors('请输入正常的重量');
            if ($data['num']<0)errors('请输入数量');
            $data['number'] = floatval($data['number']);
            $data['num'] = intval($data['num']);

            $where = ['stock_sn'=>$data['stock_sn']];
            $info = Db::name('wh_stock')->where($where)->find();

            if(empty($info))errors('该产品不存在');
            if(!empty($type_pid) && $info['type_pid'] != $type_pid)errors('出库分类错误，无法出库');

            //总库存数量=库存数量-出库数量
            $data['num'] = $info['num']-$data['num'];

            //记录
            $re = StockModel::log(1,$info,$data['number'],$user['uid']);
            if(!empty($re['msg']))errors($re['msg']);

            success('操作成功',[]);
        }

        errors('操作异常');
    }
    /**
     * 领用
     * @return mixed
     */
    public function drawGoods()
    {
        $user = $this->member;

        if ($this->request->isPost()) {
            // 获取post数据
            $data = $this->request->post();

            $type_pid = input('type_pid');
            if (empty($data['stock_sn']))errors('请扫码');
            if (empty($data['number']))errors('请输入领用数量');
            if (empty($data['archives_sn']))errors('请选择档案号');
            //获取离线状态下的用户ID
            $archives_sns = !empty($data['archives_sn'])?explode(',',$data['archives_sn']):'';
            $stock_sn = !empty($data['stock_sn'])?explode(',',$data['stock_sn'])[0]:'';
            //$numbers = !empty($data['number'])?explode(',',$data['number']):'';
            $number = $this->filterNumber($data['number']);
            $user_ids = !empty($data['uid'])?explode(',',$data['uid']):'';

            //物料信息
            $info = Db::name('wh_stock')->where(['stock_sn'=>$stock_sn])->find();
            if(empty($info))errors('该库存不存在');
            if(!empty($type_pid) && $info['type_pid'] != $type_pid)errors('领用分类错误，无法领用');
            if($number < 0)errors('请输入有效数量');
            if($number > $info['number'])errors('库存不足');
            //分类信息
            $type_info = Db::name('wh_stock_type')->where(['id'=>$type_pid])->find();
            //主物料编码
            $stock_sn_main = $info['stock_sn'];
            if(!empty($type_info['main_id']))$stock_sn_main = StockModel::addSameStock($info['stock_sn']);

            $info['cate'] = 2;//1采购单入库，2领用，3退还
            $info['post_number'] = $number;
            //按比例折算给，主物料的数量
            //稀油退还成油漆的折算比例：0.6
            $info['post_number2'] = $number2 = $number*$type_info['main_scale'];
            $use_sn = StockModel::useSn();
            $info['use_sn'] = $use_sn;

            //$order_where = [['stock_sn','=',$stock_sn_main],['archives_sn','in',$data['archives_sn']]];
            //$info['row_area'] = Db::name('wh_order_color')->where($order_where)->sum('row_area');
            $info['row_area'] = 0;

            //获取所有的未喷面积，按未喷面积进行比例分配
            $order_color_list = [];
            foreach ($archives_sns as $sk=>$archives_sn){

                $order_color = Db::name('wh_order_color')->field('*,sum(row_area) as row_area,GROUP_CONCAT(DISTINCT archives_color) as archives_color')->where([['stock_sn','=',$stock_sn_main],['archives_sn','=',$archives_sn]])->find();

                //获取未喷面积，按未喷面积进行比例分配
                $no_where = [
                    ['a.color','in',$order_color['archives_color']],
                    ['g.status','<',3],
                    ['g.archives_sn','=',$archives_sn],
                ];
                $row_no_area = Db::name('mill_order_archives_give')
                    ->alias('g')
                    ->field('a.id,sum(a.one_area) as row_area')
                    ->leftJoin('mill_order_archives a','a.id=g.archives_id')
                    ->where($no_where)
                    ->find();
                //如果未喷面积为0，则按总面积进行比例分配
                //如果有未喷面积，则按未喷面积进行比例分配
                if(!empty($row_no_area['row_area']))$order_color['row_area'] = $row_no_area['row_area'];
                //if(!empty($row_no_area['id'])){
                //    if(empty($row_no_area['row_area']))continue;
                //    $order_color['row_area'] = $row_no_area['row_area'];
                //}

                $order_color_list[$archives_sn] = $order_color;
                $info['row_area'] += $order_color['row_area'];
            }
            if(empty($order_color_list))errors('此工程已喷完');

            //遍历档案号
            $i = 1;
            $count = count($archives_sns);
            foreach ($archives_sns as $sk=>$archives_sn){

                $order_color = $order_color_list[$archives_sn];
                //如果是混合领用，且之前有过单独领用记录
                //单独设置领用编号，退还时就不计入到退还流程
                if($count > 1){
                    $use_sn_old = Db::name('wh_stock_log')->where([['stock_sn','=',$stock_sn_main],['archives_sn','=',$archives_sn],['use_sn','<>',""]])->order('use_sn desc')->value('use_sn');
                    if(!empty($use_sn_old)){
                        $use_sn_old_count = Db::name('wh_stock_use_log')->where(['use_sn'=>$use_sn_old])->count();
                        if($use_sn_old_count == 1)$info['use_sn'] = "{$use_sn}_0";
                    }
                }

                $info['order_id'] = $order_color['order_id'];
                $info['archives_sn'] = $order_color['archives_sn'];

                //分配到的数量
                $area__number = $number;//出库数量
                $area__number2 = $number2;//按比例折算给，主物料的数量，仅做领用记录用
                //如果不是最后一个档案号，则继续分配数量和比例
                if($i != $count){
                    //面积比例
                    $area_scale = round(($order_color['row_area']/$info['row_area']),4);
                    //分配到的数量
                    $area__number = round(($info['post_number']*$area_scale),2);
                    $area__number2 = round(($info['post_number2']*$area_scale),2);
                    //总数量-分配到的数量
                    $number -= $area__number;
                    $number2 -= $area__number2;
                }

                //出库记录
                $re = StockModel::log(1,$info,$area__number,$user['uid']);
                //if(!empty($re['msg']))errors($re['msg']);

                $log_id = '';
                if(!empty($re['log_id']))$log_id = $re['log_id'];

                $info['list'][] = [
                    'use_sn'            =>  $info['use_sn'],
                    'archives_sn'       =>  $archives_sn,
                    //判断是不是主物料
                    //不是主物料，则调用折算后的主物料数量，用于记录成主物料的领用记录
                    'post_number'       =>  empty($type_info['main_id'])?$area__number:$area__number2,
                    'log_id'            =>  $log_id,
                ];

                $i++;
            }

            //领用记录，记录至主物料里
            $info['stock_sn'] = $stock_sn_main;//主物料编码
            StockModel::useLog(1,$info,$user['uid']);

            success('操作成功',[]);
        }

        errors('操作异常');
    }
    /**
     * 退还
     * @return mixed
     */
    public function alsoGoods()
    {
        $user = $this->member;

        if ($this->request->isPost()) {
            // 获取post数据
            $data = $this->request->post();

            $type_pid = input('type_pid');
            if (empty($data['stock_sn']))errors('请扫码');
            if (empty($data['number']))errors('请输入退还数量');
            //if (empty($data['archives_sn']))errors('请选择档案号');
            //获取离线状态下的用户ID
            $archives_sn = input('archives_sn');
            $stock_sn = $data['stock_sn'];
            $number = $this->filterNumber($data['number']);
            $user_ids = !empty($data['uid'])?explode(',',$data['uid']):'';

            //物料信息
            $info = Db::name('wh_stock')->where(['stock_sn'=>$stock_sn])->find();
            if(empty($info))errors('该库存不存在');
            if(!empty($type_pid) && $info['type_pid'] != $type_pid)errors('退还分类错误，无法退还');
            //分类信息
            $type_info = Db::name('wh_stock_type')->where(['id'=>$type_pid])->find();
            //主物料编码
            $stock_sn_main = $info['stock_sn'];
            if(!empty($type_info['main_id']))$stock_sn_main = StockModel::addSameStock($info['stock_sn']);

            $info['cate'] = 3;//1采购单入库，2领用，3退还
            $info['post_number'] = $number;
            //按比例折算给，主物料的数量
            //稀油退还成油漆的折算比例：0.6
            $info['post_number2'] = $number2 = $number*$type_info['main_scale'];
            $info['note'] = input('note');

            //根据最近的领用记录获取档案号，并退还
            $where[] = ['stock_sn','=',$stock_sn_main];
            if(!empty($archives_sn))$where[] = ['archives_sn','=',$archives_sn];
            $use_sn = Db::name('wh_stock_use_log')->where($where)->order('create_time desc,use_sn asc')->value('use_sn');
            //if(empty($use_sn))errors('没有领用记录');
            //无领用记录，则直接入库
            if(empty($use_sn)){
                if(!empty($archives_sn))$info['archives_sn'] = $archives_sn;
                //入库记录
                StockModel::log(0,$info,$info['post_number'],$user['uid']);
                success('操作成功',[]);
            };

            $info['use_sn'] = $use_sn;
            $info['use_number'] = Db::name('wh_stock_log')->where(['use_sn'=>$use_sn])->sum('number');
            $info['list'] = Db::name('wh_stock_log')->where(['use_sn'=>$use_sn])->order('id asc')->select();

            $i = 1;
            $count = count($info['list']);
            foreach ($info['list'] as &$v){
                $v['id'] = Db::name('wh_stock_use_log')->where(['use_sn'=>$use_sn,'order_id'=>$v['order_id']])->value('id');
                //分配到的数量
                $area__number = $number;
                $area__number2 = $number2;//按比例折算给，主物料的数量，仅做领用记录用
                //如果不是最后一个物料，则继续分配数量和比例
                if($i != $count){
                    //面积比例
                    $area_scale = round(($v['number']/$info['use_number']),4);
                    //分配到的数量
                    $area__number = round(($info['post_number']*$area_scale),2);
                    $area__number2 = round(($info['post_number2']*$area_scale),2);
                    //总数量-分配到的数量
                    $number -= $area__number;
                    $number2 -= $area__number2;
                }

                $info['order_id'] = $v['order_id'];
                $info['archives_sn'] = $v['archives_sn'];
                //入库记录
                $re = StockModel::log(0,$info,$area__number,$user['uid']);

                $log_id = '';
                if(!empty($re['log_id']))$log_id = $re['log_id'];

                //判断是不是主物料
                //不是主物料，则调用折算后的主物料数量，用于记录成主物料的退还记录
                $v['post_number'] = empty($type_info['main_id'])?$area__number:$area__number2;
                $v['log_id_back'] = $log_id;

                $i++;
            }

            //退还记录，记录至主物料里
            $info['stock_sn'] = $stock_sn_main;//主物料编码
            StockModel::useLog(0,$info,$user['uid']);

            success('操作成功',[]);
        }

        errors('操作异常');
    }
    /**
     * 直接退还
     * @return mixed
     */
    public function alsoRefGoods_old()
    {
        $user = $this->member;

        if ($this->request->isPost()) {
            // 获取post数据
            $data = $this->request->post();

            $type_pid = input('type_pid');
            if (empty($data['stock_sn']))errors('请扫码');
            if (empty($data['number']))errors('请输入退还数量');
            if (empty($data['note']))errors('请输入备注');
            //if (empty($data['archives_sn']))errors('请选择档案号');
            //获取离线状态下的用户ID
            $archives_sn = input('archives_sn');
            $stock_sn = $data['stock_sn'];
            $numbers = $this->filterNumber($data['number']);
            $user_ids = !empty($data['uid'])?explode(',',$data['uid']):'';

            //物料信息
            $info = Db::name('wh_stock')->where(['stock_sn'=>$stock_sn])->find();
            if(empty($info))errors('该库存不存在');
            if(!empty($type_pid) && $info['type_pid'] != $type_pid)errors('退还分类错误，无法退还');

            $info['cate'] = 3;//1采购单入库，2领用，3退还
            $info['post_number'] = $numbers;
            $info['note'] = input('note');

            //入库记录
            StockModel::log(0,$info,$info['post_number'],$user['uid']);

            //将退还数量记录至直接出库记录里
            $log_id = Db::name('wh_stock_log')->where([['status','=',1],['note','<>',""]])->value('id');
            Db::name('wh_stock_log')->where(['id'=>$log_id])->setInc('back_name',$info['post_number']);

            success('操作成功',[]);
        }

        errors('操作异常');
    }
    /**
     * 采购单列表
     */
    public function materialList(){
        $user = $this->member;

        $pindex = max(1, intval(input('page',1)));
        $psize = 1;

        $type_pid = input('type_pid');
        $material_sn = input('material_sn');
        $material_sn = str_replace('，',',',strtoupper($material_sn));
        $material_sn_arr = explode(',',$material_sn);
        $where_sn = '';
        if(!empty($material_sn_arr) && !empty($material_sn)){
            foreach ($material_sn_arr as $sn){
                if(!empty($where_sn))$where_sn .= ' OR ';
                $where_sn .= " material_sn like '%{$sn}%'";
            }
        }

        $where = [['status','>',0]];
        if(!empty($type_pid))$where[] = ['type_pid','=',$type_pid];
        $order = 'status_time desc,id desc';

        $list = Db::name('wh_material')
            ->field("id,material_sn")
            ->where($where)
            ->where($where_sn)
            ->order($order)
            ->select();

        $total = Db::name('wh_material')
            ->where($where)
            ->count();

        success('', array('list' => $list, 'pagesize' => $psize, 'total' => $total, 'pindex' => $pindex, 'total_pages' => 1));
    }
    /**
     * 批次列表
     */
    public function batchList(){
        $user = $this->member;

        $pindex = max(1, intval(input('page',1)));
        $psize = 1;

        $archives_sn = input('archives_sn');
        $archives_sn = str_replace('，',',',strtoupper($archives_sn));
        $archives_sn_arr = explode(',',$archives_sn);
        $where_sn = '';
        if(!empty($archives_sn_arr) && !empty($archives_sn)){
            foreach ($archives_sn_arr as $sn){
                if(!empty($where_sn))$where_sn .= ' OR ';
                $where_sn .= " o.archives_sn like '%{$sn}%'";
            }
        }

        $where = [['o.status','=',1]];
        $order = 'o.status_time desc,o.id desc';

        $list = Db::name('mill_order')
            ->field("o.id,o.archives_sn,o.batch,concat(o.archives_sn,'/',o.batch) as batch_str")
            ->alias('o')
            ->where($where)
            ->where($where_sn)
            ->group('o.id')
            ->order($order)
            ->select();

        $total = Db::name('mill_order')
            ->alias('o')
            ->where($where)
            ->count();

        success('', array('list' => $list, 'pagesize' => $psize, 'total' => $total, 'pindex' => $pindex, 'total_pages' => 1));
    }
    /**
     * 工程颜色列表
     */
    public function colorList(){
        $user = $this->member;

        $type_pid = input('type_pid');
        $archives_sn = input('archives_sn');
        if(empty($archives_sn))errors('请选择档案号');
        $pindex = max(1, intval(input('page',1)));
        $psize = 1;

        $where = [['g.archives_sn','in',$archives_sn]];
        $order = 'g.supplier_color asc,g.type_id asc,g.supplier_id asc';

        $archives_sn_arr = explode(',',$archives_sn);
        foreach ($archives_sn_arr as $a_sn){
            $is_color = Db::name('wh_order_color')->where([['archives_sn','=',$a_sn]])->count();
            if(empty($is_color))errors("档案号[{$a_sn}],未定色");
        }

        $new_list = [];
        $new_list2 = [];
        $list = Db::name('wh_order_color')
            ->alias('g')
            ->field("g.*,s.title_abb as supplier_name")
            ->leftJoin('wh_supplier s','s.id=g.supplier_id')
            ->where($where)
            ->order($order)
            ->select();

        foreach ($list as $v){
            $v['k_str'] = "{$v['supplier_color']}_{$v['supplier_id']}_{$v['type_id']}";

            $new_list[$v['k_str']] = $v;

            $engineering = Db::name('mill_order')->where(['id'=>$v['order_id']])->value('engineering');
            $engineering = mb_substr($engineering,0,5);
            $new_list2[$v['k_str']][$v['archives_sn']] = [
                'engineering'   =>  $engineering,
                'archives_sn'   =>  $v['archives_sn'],
                'row_area'      =>  $v['row_area'],
            ];
        }
        $new_list = array_values($new_list);
        foreach ($new_list as &$nv){

            $nv['list'] = array_values($new_list2[$nv['k_str']]);
            unset($nv['k_str']);
        }

        $total = 9999;

        success('', array('list' => $new_list, 'pagesize' => $psize, 'total' => $total, 'pindex' => $pindex, 'total_pages' => 1));
    }
    /**
     * 供应商颜色列表
     */
    public function supplierColorList(){
        $user = $this->member;

        $pindex = max(1, intval(input('page',1)));
        $psize = 1;

        $supplier_color = input('supplier_color');

        $where = [];
        if(!empty($supplier_color))$where[] = ['s.supplier_color','like',"%{$supplier_color}%"];

        $list = Db::name('wh_stock')
            ->alias('s')
            ->field("s.stock_sn,concat(s.supplier_color,
		'(',
		tt.title,
		'/',t.title,
		'/',su.title,
		')') as supplier_color")
            ->where($where)
            ->leftJoin('wh_stock_type t','t.id=s.type_id')
            ->leftJoin('wh_stock_type tt','tt.id=s.type_pid')
            ->leftJoin('wh_supplier su','su.id=s.supplier_id')
            ->order('s.id desc')
            ->select();

        $total = 9999;

        success('', array('list' => $list, 'pagesize' => $psize, 'total' => $total, 'pindex' => $pindex, 'total_pages' => 1));
    }
    /**
     * 供应商列表
     */
    public function supplierList(){
        $user = $this->member;

        $pindex = max(1, intval(input('page',1)));
        $psize = 1;

        $supplier_color = input('supplier_color');

        $where = [['s.status','=',1]];
        if(!empty($supplier_color))$where[] = ['c.title','=',$supplier_color];

        $list = Db::name('wh_supplier_color')
            ->alias('c')
            ->field("s.id,s.title_abb as title")
            ->leftJoin('wh_supplier s','s.id=c.supplier_id')
            ->where($where)
            ->group('s.id')
            ->order('s.id desc')
            ->select();

        $total = 9999;

        success('', array('list' => $list, 'pagesize' => $psize, 'total' => $total, 'pindex' => $pindex, 'total_pages' => 1));
    }
    /**
     * 采购单商品列表
     */
    public function goodsList(){
        $user = $this->member;

        //显示采购商品 0:全部 1:已入库 2:未入库
        $is_join = input('is_join',0);
        $material_sn = input('material_sn');
        if(empty($material_sn))errors('请选择采购单号');
        $pindex = max(1, intval(input('page',1)));
        $psize = 1;

        $where = [['g.material_sn','in',$material_sn]];
        $order = 'g.id asc';

        if($is_join == 2)$where[] = ['g.status','<',2];
        $list = Db::name('wh_material_goods')
            ->alias('g')
            ->field("g.*,g.material_name as color,s.title_abb as supplier_name,t.title as type_pname,tt.title as type_name,q.title as quality")
            ->leftJoin('wh_supplier s','s.id=g.supplier_id')
            ->leftJoin('wh_stock_type t','t.id=g.type_id')
            ->leftJoin('wh_stock_type tt','tt.id=g.type_id')
            ->leftJoin('wh_supplier_quality q','q.id=g.quality')
            ->where($where)
            ->order($order)
            ->select();

        $total = 9999;

        success('', array('list' => $list, 'pagesize' => $psize, 'total' => $total, 'pindex' => $pindex, 'total_pages' => 1));
    }
    /**
     * 采购单商品详情
     */
    public function goodsDetail(){
        $user = $this->member;
        // 获取参数
        $id = input('id');

        $where[] = ['g.id','=',$id];

        $info = Db::name('wh_material_goods')
            ->alias('g')
            ->field("g.*,g.material_name as color,s.title_abb as supplier_name,t.title as type_pname,tt.title as type_name")
            ->leftJoin('wh_supplier s','s.id=g.supplier_id')
            ->leftJoin('wh_stock_type t','t.id=g.type_id')
            ->leftJoin('wh_stock_type tt','tt.id=g.type_id')
            ->where($where)
            ->find();

        success('操作成功',$info);
    }
    /**
     * 领用/退还记录
     */
    public function useList(){
        $user = $this->member;

        //手动录入的领用退还记录不做查询
        //无物料编码(stock_sn)，order_id=0的就是后台手动录入覆盖率，同时也是领用退还记录
        $is_use = input('is_use');//0：常规 1：外协出库
        $type_pid = input('type_pid');
        $stock_sn = input('stock_sn');
        $archives_sn = input('archives_sn');
        $supplier_color = input('supplier_color');
        $supplier_id = input('supplier_id');
        $pindex = max(1, intval(input('page',1)));
        $psize = 1;

        //分类信息
        $type_info = Db::name('wh_stock_type')->where(['id'=>$type_pid])->find();
        //主物料编码
        $stock_sn_main = $stock_sn;
        if(!empty($type_info['main_id']))$stock_sn_main = StockModel::addSameStock($stock_sn);

        $where = [];
        if(!empty($stock_sn_main))$where[] = ['u.stock_sn','=',$stock_sn_main];
        if(!empty($archives_sn))$where[] = ['u.archives_sn','=',$archives_sn];
        if(!empty($supplier_color)){
            if(empty($supplier_id))errors('请选择供应商');
            $where[] = ['u.model','=',$supplier_color];
            $where[] = ['u.supplier_id','=',$supplier_id];
        }
        if(empty($where))errors('没有领用记录');

        $order = 'u.create_time desc';
        //如果是稀油，则同时查询油漆库
        //8:稀油 1:油漆库
        if($type_pid == 8){
            $order = "u.type_pid desc,{$order}";
            $type_pid = '1,8';
        }
        if(empty($supplier_id))$where[] = ['u.type_pid','in',$type_pid];

        $archives_sn = '';
        $list = [];
        if(empty($is_use)){
            $use_sn = Db::name('wh_stock_use_log')->alias('u')->where($where)->order($order)->value('use_sn');
            if(empty($use_sn))errors('没有领用记录');

            $where = [['u.use_sn','=',$use_sn]];
            $order = 'u.id asc';

            $list = Db::name('wh_stock_use_log')
                ->alias('u')
                ->field("u.*,ss.title as color,ss.supplier_color,s.title_abb as supplier_name")
                ->leftJoin('wh_stock ss','ss.stock_sn=u.stock_sn')
                ->leftJoin('wh_supplier s','s.id=u.supplier_id')
                ->where($where)
                ->order($order)
                ->select();
        }
        //查询最近一次的外协出库
        else if($is_use == 1){

            $where = [['u.status','=',1],['u.note','<>',""],['u.stock_sn','=',$stock_sn]];
            //$where[] = ['u.status','=',1];
            //$where[] = ['u.note','<>',""];
            $order = 'u.create_time desc';

            $list = Db::name('wh_stock_log')
                ->alias('u')
                ->field("u.*,ss.title as color,ss.supplier_color,s.title_abb as supplier_name")
                ->leftJoin('wh_stock ss','ss.stock_sn=u.stock_sn')
                ->leftJoin('wh_supplier s','s.id=u.supplier_id')
                ->where($where)
                ->order($order)
                ->limit(1)
                ->select();
        }

        if(!empty($list)){
            foreach ($list as &$v){
                if(empty($v['archives_sn']))$v['archives_sn'] = $v['note'];
                $v['create_time'] = date('Y-m-d H:i',$v['create_time']);
                $archives_sn .= "/{$v['archives_sn']}";
            }
        }

        $total = 9999;

        success('', array('archives_sn'=>trim($archives_sn,'/'),'list' => $list, 'pagesize' => $psize, 'total' => $total, 'pindex' => $pindex, 'total_pages' => 1));
    }
    //物料条形码
    public function codePrint(){

        $pram = input();

        $style = 'margin: 0;transform: rotate(-270deg) translateY(35%) translateX(25.9%);';
        //$data = StockModel::codePrint($pram,'150mm','55mm',$style,2);
        $data = StockModel::codePrint($pram,'150mm','85mm',$style,2);

        if(!empty($data['msg']))$this->error($data['msg']);

        exit($data['html']);

    }


}
